# -*- coding: utf-8 -*-
#from django.db import connection, transaction
from datetime import datetime
from django.contrib.auth import SESSION_KEY
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models.query_utils import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.views.generic import list_detail
from django.views.generic.simple import direct_to_template
from hoj.judge.forms import SubmitForm
from hoj.judge.models import Problem, Solution, Source_code, UserProfile, Contest
from hoj.tools.debug import debug_string

def m(request):
    #for mobile device
    queryset = Problem.objects.all()
    return list_detail.object_list(
                                   request = request,
                                   queryset = queryset,
                                   template_name = 'judge/m.html',
                                   paginate_by = 20,
                                   )
def m_problem(request):
    try:
        id = int(request.GET.get('id', 1000))
        item = Problem.objects.get(problem_id = id)
    except:
        raise Http404('problem %d does not exist' % (id,))
    return render_to_response('judge/m_problem.html', {'p':item})

#refresh every n minute
def status(request):
    #problem_id
    #user_id
    #result
    #language
    queryset = Solution.objects.all()
    if request.GET:
        try:
            problem_id = request.GET.get('problem_id', None)
            user_id = request.GET.get('user_id', None)
            result = request.GET.get('result', None)
            language = request.GET.get('language', None)
        except:
            raise Http404('')
    
        condition = (
                Q(problem_id = problem_id) |
                Q(user_id = user_id) | 
                Q(result = result)
                )
        queryset = queryset.filter(condition)
        
    return list_detail.object_list(
                                   request = request,
                                   queryset = queryset,
                                   template_name = 'judge/status.html',
                                   paginate_by = 100,
                                   )
def problem(request):
    try:
        id = int(request.GET.get('id', 1000))
        item = Problem.objects.get(problem_id = id)
    except:
        raise Http404('problem %d does not exist' % (id,))
    return render_to_response('judge/problem.html', {'p':item})

def problemlist(request):
    queryset = Problem.objects.all()
    return list_detail.object_list(
                                   request = request,
                                   queryset = queryset,
                                   template_name = 'judge/problem_list.html',
                                   paginate_by = 100,
                                   )

@login_required
def submit(request):
    #use javascript like qzone
    if request.method == 'GET':
        try:
            id = int(request.GET.get('id', 1000))
        except:
            raise Http404('problem %d does not exist' % (id,))
        return render_to_response('judge/submit_form.html', {'form': SubmitForm({'problem':id})})

    if request.method == 'POST':
        form = SubmitForm(request.POST)
        #debug_string(str(request))
        if form.is_valid():
            debug_string('valid form')
            try:
                problem_id = Problem.objects.get(problem_id = int(form.cleaned_data['problem']))
                source_code = Source_code(source = form.cleaned_data['source_code'])
                source_code.save()
            except Exception, e:
                raise Http404(e)
            
            try:
                solution = Solution(
                                problem_id = problem_id,
                                language = form.cleaned_data['language'],
                                user_id = User.objects.get(id = request.session[SESSION_KEY]),
                                in_date = datetime.now(),
                                result = 'WT',
                                ip = request.META['REMOTE_ADDR'],
                                source_code = source_code,
                                compileinfo = None,
                                )
                solution.save()
            except Exception, e:
                source_code.delete()
                raise Http404(e)
            
            return HttpResponseRedirect('/judge/status/')
    
    form = SubmitForm({'problem':request.POST.get('problem', 1000)})
    return render_to_response('judge/submit_form.html', {'form': form})

def rank(request):
    queryset = UserProfile.objects.order_by('-solved')
    return list_detail.object_list(
                                   request = request,
                                   queryset = queryset,
                                   template_name = 'judge/rank.html',
                                   paginate_by = 100,
                                   ) 

def userstatus(request):
    try:
        u = User.objects.get(username = request.GET.get('user_id'))
        user_p = u.userprofile
    except:
        raise Http404('user does not exist')
    
    return render_to_response('judge/userstatus.html', {'t':user_p})

def contestlist(request):
    queryset = Contest.objects.all()
    return list_detail.object_list(
                                   request = request,
                                   queryset = queryset,
                                   template_name = 'judge/contest_list.html',
                                   paginate_by = 100,
                                   )

def showcontest(request):
    try:
        item = Contest.objects.get(contest_id = request.GET.get('contest_id'))
    except:
        raise Http404('user does not exist')
    
    queryset = item.problem.all()
    
    return render_to_response('judge/contest.html', {'object_list':queryset})

#login required
#permission required
def showsource(request):
    try:
        item = Solution.objects.get(source_code = int(request.GET.get('solution_id')))
    except:
        raise Http404('solution does not exist')
    
    return render_to_response('judge/source.html', {'t': item})